//
// WebSocketServer.cpp
//
// This sample demonstrates the WebSocket class.
//
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//

#include <iostream>
#include <fstream>
#include <chrono>
#include <thread>
#include <utility>
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/WebSocket.h"
#include "Poco/Net/NetException.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/Format.h"
#include "data.h"

#ifdef TEST

#include "clienttest.hpp"

#else

#include "client.hpp"

#endif


using Poco::Net::ServerSocket;
using Poco::Net::WebSocket;
using Poco::Net::WebSocketException;
using Poco::Net::HTTPRequestHandler;
using Poco::Net::HTTPRequestHandlerFactory;
using Poco::Net::HTTPServer;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPServerResponse;
using Poco::Net::HTTPServerParams;
using Poco::Util::ServerApplication;
using Poco::Util::Application;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::HelpFormatter;

template<typename T>
std::string to_string_with_precision(const T a_value, const int n = 6) {
    std::ostringstream out;
    out.precision(n);
    out << std::fixed << a_value;
    return out.str();
}

class PageRequestHandler : public HTTPRequestHandler {
public:
    void handleRequest(HTTPServerRequest &request, HTTPServerResponse &response) override {
        response.setChunkedTransferEncoding(true);
        response.setContentType("text/html");
        std::ostream &ostr = response.send();
        ostr << "<html>";
        ostr << "<head>";
        ostr << "<title>WebSocketServer</title>";
        ostr << "<script type=\"text/javascript\">";
        ostr << "function WebSocketTest()";
        ostr << "{";
        ostr << "  if (\"WebSocket\" in window)";
        ostr << "  {";
        ostr << "    var ws = new WebSocket(\"ws://" << request.serverAddress().toString() << "/ws\");";
        ostr << "    ws.onopen = function()";
        ostr << "      {";
        ostr << "        ws.send(\"Hello, world!\");";
        ostr << "      };";
        ostr << "    ws.onmessage = function(evt)";
        ostr << "      { ";
        ostr << "        var msg = evt.data;";
        ostr << "        alert(\"Message received: \" + msg);";
        ostr << "        ws.close();";
        ostr << "      };";
        ostr << "    ws.onclose = function()";
        ostr << "      { ";
        ostr << "        alert(\"WebSocket closed.\");";
        ostr << "      };";
        ostr << "  }";
        ostr << "  else";
        ostr << "  {";
        ostr << "     alert(\"This browser does not support WebSockets.\");";
        ostr << "  }";
        ostr << "}";
        ostr << "</script>";
        ostr << "</head>";
        ostr << "<body>";
        ostr << "  <h1>WebSocket Server</h1>";
        ostr << "  <p><a href=\"javascript:WebSocketTest()\">Run WebSocket Script</a></p>";
        ostr << "</body>";
        ostr << "</html>";
    }
};

class MyWebSocketRequestHandler : public HTTPRequestHandler {
private:
    std::string serialPortName;
    int baudRate;
public:
    MyWebSocketRequestHandler(std::string &serialPortName, int baudRate) :
            serialPortName{serialPortName}, baudRate{baudRate} {

    }

    ~MyWebSocketRequestHandler() {
        std::cout << "停止监听modbus" << std::endl;
        stop_modbus();
    };

    void handleRequest(HTTPServerRequest &request, HTTPServerResponse &response) override {
        if (!create_modbus_client(serialPortName.c_str(), baudRate)) {
            std::cout << "连接modbus串口失败！" << std::endl;
            return;
        }
        Application &app = Application::instance();
        try {
            std::ifstream f("config.json");
            if (!f.good()) {
                std::cout << "config.json无法读取" << std::endl;
                return;
            }
            nlohmann::json data = nlohmann::json::parse(f);
            std::vector<DHost> hostVec = data.get<std::vector<DHost>>();

            WebSocket ws(request, response);
            bool closed = false;
            std::thread checkSocket([&ws, &closed]() {
                char buffer[1024];
                int flags;
                do {
                    try {
                        ws.receiveFrame(buffer, sizeof(buffer), flags);
                    } catch (Poco::TimeoutException &e) {
                        std::cout << "timeout continue" << std::endl;
                    }
                } while ((flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);
                closed = true;
            });
            checkSocket.detach();
            app.logger().information("WebSocket connection established.");

            while (!closed) {
                std::vector<DetectorValue> allData;
                for (auto &host: hostVec) {
                    PushData pushData = readDetector(host);
                    if (pushData.success) {
                        allData.insert(allData.end(), pushData.detectorValues.begin(), pushData.detectorValues.end());
                    } else {
                        std::cout << pushData.errmsg << std::endl;
                    }
                }
                nlohmann::json jsonData;
                to_json(jsonData, allData);
                std::string jsonStr = jsonData.dump();
                const char *buffer = jsonStr.c_str();
                ws.sendFrame(buffer, strlen(buffer), WebSocket::FRAME_TEXT);
                std::this_thread::sleep_for(std::chrono::milliseconds(2000));
            }
            app.logger().information("WebSocket connection closed.");
        }
        catch (WebSocketException &exc) {
            app.logger().log(exc);
            switch (exc.code()) {
                case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
                    response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
                    // fallthrough
                case WebSocket::WS_ERR_NO_HANDSHAKE:
                case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
                case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
                    response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
                    response.setContentLength(0);
                    response.send();
                    break;
            }
        }
    }

private:
    PushData readDetector(const DHost &host) {
        PushData pushData;
        pushData.success = true;
        pushData.errmsg = "ok";

        if (host.Address <= 0 || host.PointCount <= 0) {
            return makeErrData("主机地址和读取点数必须大于零");
        }
        set_slave(host.Address);

        //青鸟设备一次最多读取点位数（串口一次最多传递的255字节）
        int const MAX_READ_COUNT = 60;
        //剩余点位数，开始点位地址，实际读取数量
        int left_count = host.PointCount, start_addr = 1, real_read_count = 0;
        //开始循环读取
        while (left_count > 0) {
            if (left_count > MAX_READ_COUNT) {
                real_read_count = MAX_READ_COUNT;
            } else {
                real_read_count = left_count;
            }

            float values[real_read_count];
            char err[1024] = {0};
            bool suc = read_detector(start_addr, real_read_count, values, err);
            if (!suc) {
                return makeErrData(err);
            }
            for (int i = 0; i < real_read_count; ++i) {
                std::string pointName = host.PointNames[start_addr + i - 1];
                if (pointName[0] == '#') {
                    vector<string> strings;
                    istringstream f(pointName.substr(1));
                    string s;
                    while (getline(f, s, '|')) {
                        strings.push_back(s);
                    }

                    string name = strings[0];
                    string position = strings[1];
                    string type = strings[2];
                    pushData.detectorValues.emplace_back(position, name, type,
                                                         to_string_with_precision(values[i], 2) + "ppm");
                }
            }

            left_count -= MAX_READ_COUNT;
            start_addr += real_read_count;
        }
        return pushData;

    }

    static PushData makeErrData(std::string errmsg) {
        PushData workShopData;
        workShopData.success = false;
        workShopData.errmsg = std::move(errmsg);
        return workShopData;
    }
};


class RequestHandlerFactory : public HTTPRequestHandlerFactory {
private:
    std::string serialPortName;
    int baudRate;
public:
    RequestHandlerFactory(std::string serialPortName, int baudRate) : serialPortName{serialPortName},
                                                                      baudRate{baudRate} {

    }

    HTTPRequestHandler *createRequestHandler(const HTTPServerRequest &request) override {
        Application &app = Application::instance();
        app.logger().information("Request from "
                                 + request.clientAddress().toString()
                                 + ": "
                                 + request.getMethod()
                                 + " "
                                 + request.getURI()
                                 + " "
                                 + request.getVersion());

        for (HTTPServerRequest::ConstIterator it = request.begin(); it != request.end(); ++it) {
            app.logger().information(it->first + ": " + it->second);
        }

        if (request.find("Upgrade") != request.end() && Poco::icompare(request["Upgrade"], "websocket") == 0)
            return new MyWebSocketRequestHandler(serialPortName, baudRate);
        else
            return new PageRequestHandler;
    }
};


class WebSocketServer : public Poco::Util::ServerApplication
    /// The main application class.
    ///
    /// This class handles command-line arguments and
    /// configuration files.
    /// Start the WebSocketServer executable with the help
    /// option (/help on Windows, --help on Unix) for
    /// the available command line options.
    ///
    /// To use the sample configuration file (WebSocketServer.properties),
    /// copy the file to the directory where the WebSocketServer executable
    /// resides. If you start the debug version of the WebSocketServer
    /// (WebSocketServerd[.exe]), you must also create a copy of the configuration
    /// file named WebSocketServerd.properties. In the configuration file, you
    /// can specify the port on which the server is listening (default
    /// 9980) and the format of the date/time string sent back to the client.
    ///
    /// To test the WebSocketServer you can use any web browser (http://localhost:9980/).
{
public:
    WebSocketServer() : _helpRequested{false} {
    }

    ~WebSocketServer() override {
    }

protected:
    void initialize(Application &self) override {
        loadConfiguration(); // load default configuration files, if present
        ServerApplication::initialize(self);
    }

    void uninitialize() override {
        ServerApplication::uninitialize();
    }

    void defineOptions(OptionSet &options) override {
        ServerApplication::defineOptions(options);

        options.addOption(
                Option("help", "h", "display help information on command line arguments")
                        .required(false)
                        .repeatable(false));
    }

    void handleOption(const std::string &name, const std::string &value) override {
        ServerApplication::handleOption(name, value);

        if (name == "help")
            _helpRequested = true;
    }

    void displayHelp() {
        HelpFormatter helpFormatter(options());
        helpFormatter.setCommand(commandName());
        helpFormatter.setUsage("OPTIONS");
        helpFormatter.setHeader("A sample HTTP server supporting the WebSocket protocol.");
        helpFormatter.format(std::cout);
    }

    int main(const std::vector<std::string> &args) override {
        if (_helpRequested) {
            displayHelp();
        } else {
            // get parameters from configuration file
//            unsigned short port = (unsigned short) config().getInt("WebSocketServer.Port", 9981);
//            std::string serialName = config().getString("Modbus.SerialName", "/dev/ttyUSB0");
//            int baudRate = config().getInt("Modbus.Baudrate", 9600);

            unsigned short port = 9981;
            std::string serialName ="/dev/ttyUSB0";
            int baudRate =9600;

            ServerSocket svs(port);
            HTTPServer srv(new RequestHandlerFactory(serialName, baudRate), svs, new HTTPServerParams);
            srv.start();
            // wait for CTRL-C or kill
            waitForTerminationRequest();
            srv.stop();
        }
        return Application::EXIT_OK;
    }

private:
    bool _helpRequested;
};


POCO_SERVER_MAIN(WebSocketServer)
